<?php

namespace catchAdmin\shopping\controller;

use app\common\lib\Redis;
use app\common\utils\Thumbnail;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catchAdmin\shopping\request\ClassifyRequest;
use app\common\model\ShoppingClassify as ClassifyModel;
use catcher\exceptions\FailedException;

class ShoppingClassify extends CatchController
{
    protected $classify;

    public function __construct(ClassifyModel $classify)
    {
        $this->classify = $classify;
    }

    /**
     * 列表
     *
     * @time 2020年01月09日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::success($this->classify->getList());
    }

    /**
     * 添加
     *
     * @time 2020年01月09日
     * @param ClassifyRequest $request
     * @return \think\response\Json
     */
    public function save(ClassifyRequest $request): \think\response\Json
    {
        $req = $request->post();

        //没有parent_id，默认为父级
        if (empty($req['parent_id'])) {
            $req['parent_id'] = 0;
        }

        //用原图生成缩略图并保存
        if (!empty($req['image'])) {
            $req['thumbnail_img'] = $this->convertThumbnails($req['image']);
        }

        $req['sort'] = (int)$req['sort'];
        $req['deleted_at'] = 0;
        $ret = $this->classify->save($req);

        //添加成功，添加redis
        if ($ret) {
            $this->addCacheData();
        }
        return CatchResponse::success($ret);
    }

    /**
     * 更新
     *
     * @time 2020年01月09日
     * @param $id
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update($id, CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        //用原图生成缩略图并保存
        if (!empty($req['image'])) {
            $req['thumbnail_img'] = $this->convertThumbnails($req['image']);
        }

        $ret = $this->classify->updateBy($id, $req);
        //更新成功，更新redis
        if ($ret > 0) {
            $this->addCacheData();
        }
        return CatchResponse::success($ret);
    }

    /**
     * 删除
     *
     * @time 2020年01月09日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id): \think\response\Json
    {
        $isExist = $this->classify->where('parent_id', $id)->findOrEmpty();
        if (!$isExist->isEmpty()) {
            throw new FailedException("存在子级分类，请先删除子级分类");
        }

        $ret = $this->classify->destroy($id);
        //删除成功，更新redis
        if ($ret) {
            $this->addCacheData();
        }
        return CatchResponse::success($ret);
    }

    /**
     * 添加redis缓存
     * @return void
     */
    private function addCacheData(): void
    {
        try {
            $treeData = $this->classify->order('sort', 'desc')->select()->toTree();
            $treeDataJson = json_encode($treeData, JSON_UNESCAPED_UNICODE);
            Redis::getInstance()->redis->set('shoppingClassify', $treeDataJson);
            return;
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 生成缩略图
     * @param string $image 原图片路径
     * @return string
     */
    private function convertThumbnails(string $image): string
    {
        $str = str_replace('/', '\\', $image);
        $str2 = str_replace('\files', '', $str);
        $imgPath = config('filesystem.disks.local.root').$str2;

        $newPath = pathinfo($imgPath, PATHINFO_DIRNAME) . '\\' .
            pathinfo($imgPath, PATHINFO_FILENAME) . '_thumbnail.' .
            pathinfo($imgPath, PATHINFO_EXTENSION);
        $ret = (new Thumbnail())->generateThumbnail($imgPath, $newPath);
        if (!$ret) {
            throw new FailedException('生成缩略图失败');
        }
        return $newPath;
    }
}